package com.ouman.luoliluoli.galleryfragments;

import android.content.Context;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.ouman.luoliluoli.MainActivity;
import com.ouman.luoliluoli.R;
import com.ouman.luoliluoli.adapters.HotGirlsRecyclerViewAdapter;
import com.ouman.luoliluoli.articlefragments.DailyFeedsFragment;
import com.ouman.luoliluoli.models.HotGirlsModel;
import com.ouman.luoliluoli.utils.GlobalConstants;
import com.ouman.luoliluoli.utils.GridSpacingItemDecoration;
import com.ouman.luoliluoli.utils.NetworkHelper;

import org.apache.commons.io.IOUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Random;

import static android.widget.Toast.LENGTH_SHORT;

/**
 * Created by jintian on 12/05/2017.
 */

public class HotGirlsFragment  extends Fragment {

    private RecyclerView recyclerView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private HotGirlsRecyclerViewAdapter adapter;
    private ArrayList<HotGirlsModel> hotGirlsArray;

    private NetworkHelper networkHelper;
    private Integer page;

    private OnFragmentInteractionListener mListener;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.gallery_fragment_hotgirls, container, false);
        ((MainActivity) getActivity()).setAppBarElevation(0);

        recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerViewHotGirls);
        swipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipeRefreshHotGirls);
        return rootView;
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState){
        super.onActivityCreated(savedInstanceState);
        networkHelper = new NetworkHelper();

        // page取自日期，乘以月份奇偶, 如5月1号就是, 1*1 = 1
        Calendar cal = Calendar.getInstance();
        Integer month = cal.get(Calendar.MONTH);
        Integer day = cal.get(Calendar.DAY_OF_MONTH);
        if (month % 2 == 0){
            page = 2 * day;
        }else{
            page = day;
        }
        System.out.println("今天的性感美女page" + page.toString() + "来自" + month.toString() + " " + day.toString());

        hotGirlsArray = new ArrayList<>();

        if (networkHelper.isConnect(getContext())){
            new  Thread(getHttpThread).start();
        }else {
            Toast.makeText(getActivity(), "no connection, please check your network.", Toast.LENGTH_SHORT).show();
        }

        //add swipe refresh on recycler view
        swipeRefreshLayout.setSize(SwipeRefreshLayout.DEFAULT);
        swipeRefreshLayout.setColorSchemeResources(android.R.color.black, android.R.color.holo_red_light,
                android.R.color.holo_blue_light, android.R.color.holo_purple);
        swipeRefreshLayout.setProgressViewEndTarget(true, 200);
        swipeRefreshLayout.setRefreshing(true);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // check network
                if (networkHelper.isConnect(getActivity())){
                    new  Thread(getHttpThread).start();
                }else {
                    Toast.makeText(getActivity(), "no connection, please check your network.", Toast.LENGTH_SHORT).show();
                }
                swipeRefreshLayout.setRefreshing(false);
            }
        });
        StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
//        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        // TODO: here I changed!!!!!!!
        manager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);

        recyclerView.setLayoutManager(manager);
        recyclerView.setHasFixedSize(true);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addItemDecoration(new GridSpacingItemDecoration(2,10,true));

        adapter = new HotGirlsRecyclerViewAdapter(getActivity(), hotGirlsArray);
        recyclerView.setAdapter(adapter);


    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof DailyFeedsFragment.OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFragmentInteractionListener {
        void onFragmentInteraction(Uri uri);
    }

    public class SpaceItemDecoration extends RecyclerView.ItemDecoration{
        private int space;
        public SpaceItemDecoration(int space) {
            this.space = space;
        }
        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            if(parent.getChildPosition(view) != 0)
                outRect.top = space;
        }
    }


    private  Thread getHttpThread = new Thread(){
        public void run(){
            //In here we solve http request to get data
            swipeRefreshLayout.setRefreshing(true);
            HttpURLConnection connection = null;
            try {
                GlobalConstants globalConstants = new GlobalConstants();

                String urlAPI = globalConstants.API_TNGOU + page.toString();
                System.out.println("Tngou url: " + urlAPI);
                URL url = new URL(urlAPI);
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                if (connection.getResponseCode() == 200){
                    InputStream is = connection.getInputStream();
                    String result = IOUtils.toString(is);
                    System.out.println(result);
                    is.close();
                    JSONObject jsonObject = new JSONObject(result);
                    JSONArray jArray = jsonObject.getJSONArray("tngou");

                    if (jArray.length() == 0){
                        // indicates no more data
                        Message msg = Message.obtain();
                        msg.what = 1;
                        getHttpHandler.sendMessage(msg);
                    }else{
                        for (int i=0; i<jArray.length(); i++){
                            try {
                                JSONObject dataObject = jArray.getJSONObject(i);
                                String imageUrl = dataObject.getString("img");
                                String title = dataObject.getString("title");

                                HotGirlsModel hotGirlsModel = new HotGirlsModel();
                                hotGirlsModel.setImg(imageUrl);
                                hotGirlsModel.setTitle(title);
                                hotGirlsArray.add(0, hotGirlsModel);

                            } catch (JSONException e){
                            }
                        }
                        if (!hotGirlsArray.isEmpty()){
                            Message msg = Message.obtain();
                            msg.what = 0;
                            getHttpHandler.sendMessage(msg);
                        }else{
                            Message msg = Message.obtain();
                            msg.what = 1;
                            getHttpHandler.sendMessage(msg);
                        }
                    }
                }
            } catch (IOException e){
                e.printStackTrace();
            } catch (JSONException e){
                e.printStackTrace();
            } finally{
                if (connection != null){
                    connection.disconnect();
                }
            }

        }
    };
    private Handler getHttpHandler = new Handler(){
        public void handleMessage(Message msg){
            if (msg.what == 0){
                //add data stop refresher and send to adapter data
                //changed
                swipeRefreshLayout.setRefreshing(false);
                adapter.notifyDataSetChanged();
                page += new Random().nextInt(30);
            }else if (msg.what == 1){
                Toast.makeText(getActivity(), "请注意你的...肾...", LENGTH_SHORT).show();
                swipeRefreshLayout.setRefreshing(false);
            }
        }
    };
}
